package com.weibo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.weibo.common.util.FaceFormat;
import com.weibo.common.util.PageResult;
import com.weibo.dao.*;
import com.weibo.pojo.*;
import com.weibo.service.WeiBoService;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 服务层
 * @ClassName WeiBoServiceImpl
 * @Author 天火
 * @Date 2019-03-01
 * @Version 1.0
 */
public class WeiBoServiceImpl implements WeiBoService {

    @Autowired
    private WeiboTabMapper weiboTabMapper;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MainDao mainDao;

    @Autowired
    private SecondMapper secondMapper;

    @Autowired
    private FriendMapper friendMapper;



    @Override
    public PageResult findPageById(Integer pageNum, Integer pageSize) {
        //注入服务
        PageHelper.startPage(pageNum, pageSize);
        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        criteria.andMStateNotEqualTo(1L);
        example.setOrderByClause("m_date DESC");
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);
        weiiBoPojos = FaceFormat.formt(weiiBoPojos);
        for(WeiiBoPojo weibo :weiiBoPojos){

            if(weibo.getmLike()>0){
                weibo.setB(true);
            }
            else {
                weibo.setB(false);
            }
            User user = userDao.findUserById(weibo.getuId());
            //格式化日期。年月，日，时间
            weibo.setUser(user);
            weibo.setYearAndMonth(weibo.getPublishTime().substring(0,7).replace('-','/'));
            weibo.setDay(weibo.getPublishTime().substring(7,10));
            weibo.setHour(weibo.getPublishTime().substring(10,16));
        }
        Page<WeiiBoPojo> pageWeibo = (Page<WeiiBoPojo>) weiiBoPojos;
        PageResult pageResult = new PageResult();
        pageResult.setTotals((int)pageWeibo.getTotal());
        pageResult.setPageTotals(pageWeibo.getPages());

        pageResult.setRows(pageWeibo.getResult());
        return pageResult;
    }

    /**
     * 查询用户关注的好友微博信息
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult findPageById(Integer pageNum, Integer pageSize, Long userId) {
        //注入服务

        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        List<Long> ids = friendMapper.findFriendByuId(userId);
        if(ids.size()!=0){
            criteria.andUIdIn(ids);
        }

        criteria.andMStateNotEqualTo(1L);
        example.setOrderByClause("m_date DESC");
        PageHelper.startPage(pageNum, pageSize);
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);
        weiiBoPojos = FaceFormat.formt(weiiBoPojos);
        for(WeiiBoPojo weibo :weiiBoPojos){
            if(weibo.getmLike()!=null){
                if(weibo.getmLike()>0){
                    weibo.setB(true);
                }
            }
            else {
                weibo.setB(false);
            }
            User user = userDao.findUserById(weibo.getuId());
            weibo.setUser(user);
        }
        weiiBoPojos = FaceFormat.formt(weiiBoPojos);
        Page<WeiiBoPojo> pageWeibo = (Page<WeiiBoPojo>) weiiBoPojos;
        PageResult pageResult = new PageResult();
        pageResult.setTotals((int)pageWeibo.getTotal());
        pageResult.setPageTotals(pageWeibo.getPages());

        pageResult.setRows(pageWeibo.getResult());
        return pageResult;
    }

    @Override
    public Long weiboLike(Long weiboId, Long likeId) {
        Long likeNum = 0L;
        Date date = new Date(new java.util.Date().getTime());
        LikeTab likeTab = new LikeTab();
        likeTab.setWeiboId(weiboId);
        likeTab.setLikeUserId(likeId);
        likeTab.setLikeDate(date);
        try {

             LikeTab wLike = mainDao.findweiboLike(weiboId,likeId); 	//wLike 用来判断用户是否对该微博点过赞
            likeTab.setBeLikeId(weiboTabMapper.selectByPrimaryKey(weiboId).getuId());
            if(wLike ==null){
                //没有赞过该微博
                mainDao.likeWeibo(likeTab);
            }else if(wLike != null){
                //赞过该微博，再次点赞取消点赞
                mainDao.disLikeWeibo(likeTab);
            }
            //查找微博点赞数
            likeNum = mainDao.findWeiboLikeNumber(weiboId);
            //更新微博点赞数
            Weibo weibo = weiboTabMapper.selectByPrimaryKey(weiboId);
            weibo.setmLike(likeNum);
            weiboTabMapper.updateByPrimaryKey(weibo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeNum;
    }

    @Override
    public Long weiboTrans(long wId, long uId) {
        Long transNum = 0L;
        Date date = new Date();
        try {
            Weibo weibo = weiboTabMapper.selectByPrimaryKey(wId);	//要转发的微博
            WeiiBoPojo transWeibo = new WeiiBoPojo();			//用户转发的微博
            WeiboTrans trans = new WeiboTrans();

            User user = userDao.findUserById(weibo.getuId());		//微博的第一个转发者
            User transUser = userDao.findUserById(uId);		 //要转发的用户

            transWeibo.setUser(transUser);
            transWeibo.setmDate(date); 	//设置转发时间
            transWeibo.setuId(uId);	//转发用户
            transWeibo.setmImage(weibo.getmImage());		//转发微博图片
            transWeibo.setmBody("转发<a href=\"user_index?userId="+
                    user.getId()+"\" style='text-decoration:none' \">"+"@"+user.getNickName()+"</a> "+weibo.getmBody());	//用户转发微博内容

            weiboTabMapper.insertSelective(transWeibo);

            //组装trans数据
            trans.setWeiboId(wId);
            trans.setTransUserId(uId);
            trans.setBeTransUserId(user.getId());
            trans.setTransDate(date);

            //保存转发信息
            mainDao.saveTrans(trans);

            transNum = mainDao.findWeibotransNumber(weibo.getmId());		//获取微博转发数

            //更新微博信息\
            weibo.setmTranum(transNum);
           weiboTabMapper.updateByPrimaryKeySelective(weibo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return transNum;
    }

    @Override
    public Long weiboComment(WeiboComm weiboComm) {
        Long commNum = 0L;
        try {
            Date date = new Date();
            weiboComm.setBeCommentId(weiboTabMapper.selectByPrimaryKey(weiboComm.getWeiboId()).getuId());//得道该微博用户ID
            weiboComm.setCommentLike(0); 	//默认点赞数为0
            weiboComm.setCommentDate(date);
            //保存评论信息
            mainDao.saveWeiboComm(weiboComm);
            Weibo weibo = weiboTabMapper.selectByPrimaryKey(weiboComm.getWeiboId());
            //查找微博评论数
            commNum = mainDao.findCommNum(weiboComm.getWeiboId());
            weibo.setmComnum(commNum);
            //更新微博评论数目
            weiboTabMapper.updateByPrimaryKeySelective(weibo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return commNum;
    }

    @Override
    public Long findCommNum(long wId) {
        Long commNum = 0L;
        try {
            commNum = mainDao.findCommNum(wId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return commNum;
    }

    @Override
    public PageResult findWeiboComm(long wId, int page, int zt) {
        List<WeiboComm> list;
        PageResult pageResult = new PageResult();
        PageHelper.startPage(page,5);
        if(zt == 1){
            //上一页
            PageHelper.startPage(page-1,5);
        }else if(zt == 2){
            //下一页
            PageHelper.startPage(page+1,5);
        }
        User user = null;
        try {
            list = mainDao.findWeiboComm(wId);
            list = FaceFormat.commFormt(list);
            for(int i=0;i<list.size();i++){
                user = userDao.findUserById(list.get(i).getCommentId());
                DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               list.get(i).setCommentDateStr(simpleDateFormat.format(list.get(i).getCommentDate()));
                list.get(i).setCommUser(user);		//微博评论人信息
            }
            Page<WeiboComm> pageWeiboComm = (Page<WeiboComm>) list;

            pageResult.setTotals((int)pageWeiboComm.getTotal());
            pageResult.setRows(pageWeiboComm.getResult());
            pageResult.setPageTotals(pageWeiboComm.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }

    @Override
    public void weiboCollect(User user, Long wId) {
        try {
            Weibo w = weiboTabMapper.selectByPrimaryKey(wId);
            WeiboCollect collect = new WeiboCollect(w, user.getId());
            mainDao.weiboCollect(collect);
            w.setmColnum(w.getmColnum() + 1);
            user.setCollect(user.getCollect()+1);
            userDao.updateUserCollectNum(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void publishWeibo(Weibo weibo) {
        try {
            Date date = new Date();
            weibo.setmColnum(0L);
            weibo.setmTranum(0L);
            weibo.setmComnum(0L);
            weibo.setmLike(0L);
            weibo.setmDate(date);
            weibo.setmState(0L);
            weibo.setmTState(0L);
            weibo.setmTag(0L);
            weiboTabMapper.insert(weibo);
        } catch (Exception e) {
            //throw new WeiboServiceException("发布失败，请重试！");
            e.getStackTrace();
        }
    }

    /**
     * 查询推荐用户实现
     * @param uId
     * @return
     */
    @Override
    public List<User> findTuijianById(Long uId) {
        List<User> users = secondMapper.findTuijianUserByUserId(uId);
        return users;
    }

    @Override
    public PageResult seachWeibopojoList(String key , int page, String ac) {
       PageResult result = new PageResult();
        try {
            if("weibotwo".equals(ac)){
                //模糊搜索对应关键字的微博
                PageHelper.startPage(page,5);
                WeiboTabExample example = new WeiboTabExample();
                WeiboTabExample.Criteria criteria = example.createCriteria();
                criteria.andMBodyLike("%"+key +"%");
                List<WeiiBoPojo> weiboList = weiboTabMapper.selectByExample(example);
                for(WeiiBoPojo weiiBoPojo : weiboList){
                    weiiBoPojo.setUser(userDao.findUserById(weiiBoPojo.getuId()));
                    weiiBoPojo.setmBody(FaceFormat.keyFormt(weiiBoPojo.getmBody(), key));
                }
                weiboList = FaceFormat.formt(weiboList);
                Page<WeiiBoPojo> weiiBoPojos = (Page<WeiiBoPojo>) weiboList;
                if(weiiBoPojos.size()==0){
                    result=null;
                    return result;
                }
                result.setRows(weiiBoPojos.getResult());
                result.setTotals((int)weiiBoPojos.getTotal());
                result.setPageTotals(weiiBoPojos.getPages());
            }else if("user".equals(ac)){
                //模糊搜索对应关键字的用户
                PageHelper.startPage(page,5);
                List<User> userList = userDao.findUserBySeach(key);
                for(User user :userList){
                    user.setNickName(FaceFormat.keyFormt(user.getNickName(),key));
                }
                Page<User> users = (Page<User>) userList;
                result.setRows(users.getResult());
                result.setTotals((int)users.getTotal());
                result.setPageTotals(users.getPages());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public WeiiBoPojo findWeiboByWId(Long wId) {

        User user ;
        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        criteria.andMIdEqualTo(wId);
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);

        FaceFormat.formt(weiiBoPojos);
        user = userDao.findUserById(weiiBoPojos.get(0).getuId());
        weiiBoPojos.get(0).setUser(user);
        return weiiBoPojos.get(0);
    }


}
